package com.meida.listener;

import cn.hutool.core.map.MapUtil;
import com.meida.common.base.constants.CommonConstants;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.configuration.OpenCommonProperties;
import com.meida.common.constants.QueueConstants;
import com.meida.mq.annotation.MsgListener;
import com.meida.starter.fileview.conver.MediaUtils;
import com.meida.starter.fileview.conver.OfficeUtils;
import com.meida.starter.fileview.result.ConvertResult;
import com.meida.starter.rabbitmq.config.RabbitComponent;
import com.meida.starter.rabbitmq.core.BaseRabbiMqHandler;
import com.meida.starter.rabbitmq.listener.MqListener;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.messaging.handler.annotation.Header;

import java.io.File;
import java.util.Map;

/**
 * 转换PDF
 *
 * @author zyf
 */
@RabbitComponent(value = "convertPdfRabbitMqListener")
@Slf4j
public class ConvertPdfRabbitMqListener extends BaseRabbiMqHandler<EntityMap> {

    @Autowired
    private OpenCommonProperties openCommonProperties;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @MsgListener(queues = QueueConstants.QUEUE_UPLOAD_CONVERT)
    public void onMessage(EntityMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<EntityMap>() {
            @Override
            public void handler(EntityMap map, Channel channel) {
                String localPath = map.get("localPath");
                File file = new File(localPath);
                try {
                    if (file.exists()) {
                        File targetDir = new File(file.getParentFile(), "pdf");
                        Integer allowConvert = MapUtil.getInt(map, "allowConvert");
                        ConvertResult result = new ConvertResult(null, false);
                        switch (allowConvert) {
                            case 1:
                                result = OfficeUtils.convertPdf(file, targetDir, openCommonProperties.getOfficePath());
                                break;
                            case 2:
                                //视频转换
                                result = MediaUtils.convertMedia(file, targetDir, openCommonProperties.getFfmpegPath(), CommonConstants.INT_2);
                                break;
                            case 3:
                                //音频转换
                                result = MediaUtils.convertMedia(file, targetDir, openCommonProperties.getFfmpegPath(), CommonConstants.INT_3);
                                break;
                        }
                        if (result.isSuccess()) {
                            String ossPath = map.get("ossPath");
                            log.info("转换回调,文件路径:" + ossPath);
                            if (FlymeUtils.isNotEmpty(ossPath)) {
                                String pdfPath = getPdfPath(ossPath);
                                updatePdf(baseMap, pdfPath);
                            }
                        } else {
                            log.error("转换失败:" + localPath);
                        }

                    } else {
                        log.info("文件不存在:", localPath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void updatePdf(EntityMap params, String pdfPath) {
        String categoryId = params.get("categoryId");
        Long fileId = params.getLong("fileId");
        if (FlymeUtils.allNotNull(categoryId, fileId)) {
            String selSql = "select tableName from arc_category where categoryId=?";
            log.info("查询表名" + selSql);
            Map<String, Object> category = jdbcTemplate.queryForMap(selSql, categoryId);
            if (FlymeUtils.isNotEmpty(category)) {
                EntityMap map = new EntityMap(category);
                String tableName = map.get("tableName");
                if (FlymeUtils.isNotEmpty(tableName)) {
                    String update = "update arc_original" + tableName;
                    String updateSql = update + " set filePath=? where arcOriginalId=?";
                    log.info("更新PDF路径" + updateSql);
                    jdbcTemplate.update(updateSql, pdfPath, fileId);
                }
            }

        }
    }

    private String getPdfPath(String path) {
        int s = path.lastIndexOf("/");
        int e = path.lastIndexOf(".");
        String a = path.substring(0, s + 1);
        String b = path.substring(s, e);
        return a + "pdf" + b + ".pdf";
    }

}
